import requests
import time
import os
from os import system
import datetime
import sys
from pidModule import writePid
#prettytable 并非 python 的内置库，通过 pip install prettytable即可安装
from prettytable import PrettyTable
import re
#pip install texttable
from texttable import Texttable

system("title tushareLimitUp") #给终端命名

# 获取当前脚本所在目录路径
#script_dir = os.path.dirname(os.path.realpath(__file__))

pidPath = "tushareLimitUp.pid"

# 修改舍入方式为四舍五入，解决round 遇5不进的问题
def round_up_down(dst,num = 2):
    dst = float(dst)
    if(dst * pow(10,num+1)%10 == 5):
        ans = math.ceil(dst * pow(10, num)) / pow(10, num)
    else:
        ans = round(dst, num)
    return ans

#字符串获取纯数字
def extract_numbers(text):
    num_str = ''
    # 提取字符串中的数字
    for char in text:
        if char.isnumeric():
            num_str += char
    # 输出匹配结果
    return num_str



def get_data_from_api(api_url):  
    try:
        # 发送GET请求   
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'}
        response = requests.get(api_url, headers=headers,timeout=30)
        # 检查请求是否成功  
        if response.status_code == 200:  
            # 解析返回的JSON数据  
            data = response.json()  
            return data  
        else:  
            print(f"请求失败，状态码：{response.status_code}")  
            exit()
    except Exception as e:
        print(f"异常信息：{str(e)}")
        exit()

def printTableList(data):
    # 使用sorted()函数按时间戳排序
    sorted_data = sorted(data, key=lambda x: x['first_limit_up'])
    #print(apiData)

    # 创建PrettyTable实例
    #table = PrettyTable()

    # 创建一个Texttable实例
    table = Texttable()
    table.set_chars(['-', '|', '+', '-'])
    table.set_max_width(200)
    # PrettyTable设置表头
    #table.field_names = ["id","code","price", "stock_name","surge_reason", "up_days","first_limit_up","last_limit_up","down_times","shizhi","zhangdiefu"]
    # Texttable设置表头
    table.header(["id","code","price", "stock_name","surge_reason", "up_days","first_limit_up","last_limit_up","down_times","shizhi","zhangdiefu"])
    i=1
    # 遍历数据并添加到PrettyTable
    for item in sorted_data:
        if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
            continue;

        try:
            surge_reason = (item['surge_reason']['related_plates'][0]['plate_name'])
        except Exception as e:
            error=e
            surge_reason = ''
        
        code = extract_numbers(item['symbol'])

        # 将时间戳转换为datetime对象
        first_limit_up = datetime.datetime.fromtimestamp(item['first_limit_up'])
        last_limit_up = datetime.datetime.fromtimestamp(item['last_limit_up'])
         
        # 使用time模块的strftime方法格式化时分秒
        first_limit_up = first_limit_up.time().strftime('%H:%M:%S')
        last_limit_up = last_limit_up.time().strftime('%H:%M:%S')


        table.add_row([i,str(code),str(item['price']), str(item['stock_chi_name']),surge_reason, str(item['limit_up_days']), str(first_limit_up), str(last_limit_up),str(item['break_limit_up_times']),str(round_up_down(item['non_restricted_capital']/100000000)),str(round(item['change_percent']*100,2))+"%"])
        
        #print(item['price'])
        i=i+1
        #exit()
 
    #输出PrettyTable
    #print(table)
    #输出texttable
    print(table.draw())


def main():
    #抓取的选股宝网页地址：https://xuangubao.cn/dingpan
    #https://codingchangeworld.com/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/ry/detail_article/5211713346760
    os.system("cls")   # 清屏操作
    url =f'https://flash-api.xuangubao.cn/api/pool/detail?pool_name=limit_up'
    print("当前时间："+ str(datetime.datetime.now())) 
    print(url)
    print('')
    apiData=get_data_from_api(url)

    printTableList(apiData['data'])

    
        
if __name__ == '__main__':
    
    #写入进程pid
    writePid(pidPath)

    while True:
        main()
        time.sleep(5)
    


